import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home',
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('@/components/layout/Home.vue'),
      redirect: '/home/Recommend',
      children: [
        {
          path: 'Recommend',
          name: 'Recommend',
          component: () => import('@/views/Recommend.vue'),
        },
        {
          path: 'Publish',
          name: 'Publish',
          component: () => import('@/views/Publish.vue'),
          meta: {
            requiresAuth: true,
          },
        },
        {
          path: 'Nearby',
          name: 'Nearby',
          component: () => import('@/views/Nearby.vue'),
          meta: {
            requiresAuth: true,
          },
        },
        {
          path: 'Message',
          name: 'Message',
          component: () => import('@/views/Message.vue'),
          meta: {
            requiresAuth: true,
          },
        },
        {
          path: 'Mine',
          name: 'Mine',
          component: () => import('@/views/Mine.vue'),
          meta: {
            requiresAuth: true,
          },
          redirect: '/home/Mine/published', // 重定向到子路由
          children: [
            {
              path: 'published',
              name: 'published',
              component: () => import('@/components/mine/Published.vue'),
            },
            {
              path: 'sold',
              name: 'sold',
              component: () => import('@/components/mine/Sold.vue'),
            },
            {
              path: 'purchased',
              name: 'purchased',
              component: () => import('@/components/mine/Purchased.vue'),
            },
            {
              path: 'collected',
              name: 'collected',
              component: () => import('@/components/mine/Collected.vue'),
            },
          ],
        },
      ],
    },
    {
      path: '/search',
      name: 'search',
      component: () => import('@/views/Search.vue'),
    },
    {
      path: '/order/create',
      name: 'CreateOrder',
      component: () => import('@/views/order/CreateOrder.vue'),
      meta: {
        requiresAuth: true,
      },
    },
    {
      path: '/payment/pay',
      name: 'Pay',
      component: () => import('@/views/payment/Pay.vue'),
      meta: {
        requiresAuth: true,
      },
    },
  ],
})
// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  // 既没有token，访问的又不是login，就要拦截
  if (!userStore.Authorization && to.meta.requiresAuth) {
    ElMessage.warning('需要登录后才能访问~')
    next(false) // 中断导航
  } else {
    next()
  }
})
export default router
